package org.hsc.httpProxy;

import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpProtocolDecoder  extends CumulativeProtocolDecoder {
	private static Logger logger = LoggerFactory.getLogger(HttpProtocolDecoder.class); 
	
	private Pattern pattern= Pattern.compile("(?<=Host:\\s)\\S*\\b");
	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,ProtocolDecoderOutput out) throws Exception {
		
		ProxyBean bean=new ProxyBean();
		
		logger.debug("数据大小："+in.limit());
		String rst=in.getString(Charset.defaultCharset().newDecoder());
		
		logger.debug("get data:"+rst);
		
		Matcher matcher = pattern.matcher(rst);
	    if (matcher.find()) {
	    	String[] str= matcher.group(0).split(":");
	    	bean.setHost(str[0]);
	    	bean.setPost((str.length>1)?Integer.parseInt(str[1]):80);
	    	
	    	bean.setData(rst);
	    	out.write(bean);
	    }else{
	    	logger.warn("not find request host");
	    	out.write(null);
	    }
		
		return true;
	} 

}
